package com.sqs.config;

import com.sqs.interceptor.JwtTokenUserInterceptor;
import com.sqs.interceptor.PublicApiRateLimiterInterceptor;
import com.sqs.json.JacksonObjectMapper;
import com.sqs.limiter.IpRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;


@Slf4j
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {


    @Autowired
    private JwtTokenUserInterceptor jwtTokenUserInterceptor;
    @Autowired
    private PublicApiRateLimiterInterceptor publicApiRateLimiterInterceptor;

    /**
     * 注册自定义拦截器
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry){
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenUserInterceptor)
                .addPathPatterns("/user/**")
                .addPathPatterns("/session/**")
                .addPathPatterns("/repository/**")
                .addPathPatterns("/knowledgefile/**")
                .addPathPatterns("/common/**")
                .addPathPatterns("/chat/**")
                .excludePathPatterns("/user/enroll")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/user/status/**")
                .excludePathPatterns("/common/captcha")
                .excludePathPatterns("/common/test/**");
        registry.addInterceptor(publicApiRateLimiterInterceptor)
                .addPathPatterns("/common/captcha")
                .addPathPatterns("/user/enroll")
                .addPathPatterns("user/login");
    }

    /**
     * 扩展Spring MVC框架的消息转换器
     * @param converters
     * */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        log.info("扩展消息转换器...");

        //创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //需要为消息转换器设置一个对象转换器
        converter.setObjectMapper(new JacksonObjectMapper());
        //将自己的消息转换器加入到容器中
        converters.add(0, converter);
    }
}
